//
//  RYQuerenDIngdanViewController.swift
//  SheYangBigData
//
//  Created by 宋海胜 on 2021/1/13.
//  Copyright © 2021 叁拾叁. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
import SwiftDate

class RYQuerenDIngdanViewController: SYBaseViewController, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
    
    
    var kuaidiModels:[RYKuaidiModel]!
    var peisongZhouqiModels:[RYKuaidiModel]!
    var model: RYProductDetailModel!
    var addressModel: RYAddressListModel!
    var num: Int!
    
    var params: [String: String] = [:]
    fileprivate var bottomView: RYYQueRenToolView = RYYQueRenToolView()
    
    var tableView: UITableView!
    let navView: SYBaseView = SYBaseView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: NAV_HEIGHT))
    let biaoqian: RYBiaoqianChoiceView = RYBiaoqianChoiceView(frame: CGRect(x: 0, y: NAV_HEIGHT, width: SCREEN_WIDTH, height: 40))
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.enableAutoToolbar = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enable = false
        IQKeyboardManager.shared.enableAutoToolbar = false
    }
    
    init(params: RYProductDetailModel, num: Int) {
        super.init(nibName: nil, bundle: nil)
        self.model = params
        self.num = num
        let zongjia: Double = Double(params.adoptPrice ?? "0")! * Double(num)
        
        self.params = ["farmProductId":"\(params.id ?? "")",
                       "adoptNumber":"\(params.serialNumber ?? "")",
                       "adoptTime":"\(params.productionCycleBegin ?? "")",
                       "predictMatureTime":"\(params.productionCycleEnd ?? "")",
                       "orderQuantity":"\(num)",
                       "orderPrice":"\(zongjia)",
                       "payWay":"1"
        ]
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setTableView()
        self.title = "确认订单"
        setupBottomView()
        //        self.view.backgroundColor = Constant.bgViewColor
        getPeisongData(290)
        getPeisongData(292)
    }
    
    func paramsIsEmpty() -> Bool {
        if let v = self.params["deliveryWay"] {
            if v.isEmpty {
                self.sy_toast("请填写配送方式")
                return true
            }
        } else {
            self.sy_toast("请填写配送方式")
            return true
        }
        if let v = self.params["shippingAddressId"] {
            if v.isEmpty {
                self.sy_toast("请填写配送地址")
                return true
            }
        } else {
            self.sy_toast("请填写配送地址")
            return true
        }
        if let v = self.params["adoptUserName"] {
            if v.isEmpty {
                self.sy_toast("请填写姓名")
                return true
            }
        } else {
            self.sy_toast("请填写姓名")
            return true
        }
        if let v = self.params["adoptUserContact"] {
            if v.isEmpty {
                self.sy_toast("请填写联系方式")
                return true
            }
            if !v.checkIsMobileNum() {
                self.sy_toast("请填写正确手机号")
                return true
            }
        } else {
            self.sy_toast("请填写联系方式")
            return true
        }
        if let v = self.params["deliveryCycle"] {
            if v.isEmpty {
                self.sy_toast("请填写配送周期")
                return true
            }
        } else {
            self.sy_toast("请填写配送周期")
            return true
        }
        
        
        
        if let v = self.params["payWay"] {
            if v.isEmpty {
                self.sy_toast("请填写支付方式")
                return true
            }
        } else {
            self.sy_toast("请填写支付方式")
            return true
        }
        
        return false
    }
    
    /*
     
     {
     "farmProductId":2,     产品id
     "adoptNumber":"DLC00343",      编号
     "adoptTime":"2020-09-20",      生产周期开始日期
     "predictMatureTime":"2021-03-04",      生产周期结束日期
     "orderQuantity":2,     数量
     "orderPrice":1000,     总价
     
     "deliveryWay":1,       配送方式 (配送方式列表中item的id)
     "shippingAddressId":1,     配送地址id
     "adoptUserName":"范文涛",     认养人姓名
     "adoptUserContact":"18561598898",      认养人联系方式
     "deliveryCycle":"165",     配送周期 (配送周期列表中item的id)
     "payWay":1     支付方式（1微信支付2支付宝支付3余额支付）
     remarks     备注
     }
     */
    func getBuy() {
        if paramsIsEmpty() {
            return
        }
        requestVM.baseRequest(disposeBag: dispose, type: .nongchangProductBuy(dic: self.params), modelClass: SGBaseModel<RYXiaDanModel>.self) {[weak self] (res) in
            if let `self` = self {
                let model:RYXiaDanModel = res.data ?? RYXiaDanModel()
                self.getPaySuccess(["id":model.id ?? "", "farmProductId":"\(model.farmProductId ?? 0)"])
            }
            
        } Error: {
            
        }
        
    }
    
    /*
     {
         "pid":291
     }
     */
    func getPeisongData(_ pid: Int) {
        requestVM.baseRequest(disposeBag: dispose, type: .peisongStyle(pid: pid), modelClass: SGBaseNoPageListModel<RYKuaidiModel>.self) {[weak self] (res) in
            if let `self` = self {
                if pid == 290 {
                    
                    self.kuaidiModels = res.data ?? [RYKuaidiModel]()
                } else {
                    self.peisongZhouqiModels = res.data ?? [RYKuaidiModel]()
                }
            }
            
        } Error: {
            
        }
        
    }
    
    /*
     {
         "id":18,
         "farmProductId":2
     }
     */
    func getPaySuccess(_ dic:[String: String]) {
        requestVM.baseRequest(disposeBag: dispose, type: .paySuccess(dic: dic), modelClass: SGBaseNoPageListModel<RYKuaidiModel>.self) {[weak self] (res) in
            if let `self` = self {
                self.bottomView.setAlert()
            }
            
        } Error: {
            
        }
        
    }
    
    func setTableView() {
        
        //创建表格视图
        self.tableView = UITableView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-BOTTOM_SAFE_HEIGHT-49.autoWidth()), style:.grouped)
        self.tableView.separatorStyle = .none
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView!.register(RYQuerenXinxiCell.self, forCellReuseIdentifier: "RYQuerenXinxiCell")
        self.tableView!.register(RYQuerenQuanCell.self, forCellReuseIdentifier: "RYQuerenQuanCell")
        self.tableView!.register(RYQuerenPeisongCell.self, forCellReuseIdentifier: "RYQuerenPeisongCell")
        self.tableView!.register(RYQuerenDizhiCell.self, forCellReuseIdentifier: "RYQuerenDizhiCell")
        self.tableView!.register(RYQuerenRenCell.self, forCellReuseIdentifier: "RYQuerenRenCell")
        self.tableView!.register(RYQuerenPayCell.self, forCellReuseIdentifier: "RYQuerenPayCell")
        
        self.tableView.backgroundColor = Constant.bgViewColor
        self.view.addSubview(self.tableView!)
    }
    
    fileprivate func setupBottomView() {
        bottomView.frame = CGRect(x: 0, y: SCREEN_HEIGHT - BOTTOM_SAFE_HEIGHT - 49.autoWidth(), width: SCREEN_WIDTH, height: 49.autoWidth())
        bottomView.currentVC = self
        bottomView.configure(model.adoptPrice ?? "")
        bottomView.alert.sure.addAction {[weak self] in
            if let `self` = self {
                self.popVC()
                self.removeVC(RYQuerenDIngdanViewController.self)
            }
        }
        view.addSubview(bottomView)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 6
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell: RYQuerenXinxiCell? = tableView.dequeueReusableCell(withIdentifier: "RYQuerenXinxiCell") as? RYQuerenXinxiCell
            cell?.selectionStyle = .none
            cell!.currentVC = self
            cell?.configure(model, num)
            return cell!
        } else if indexPath.row == 1 {
            let cell: RYQuerenQuanCell? = tableView.dequeueReusableCell(withIdentifier: "RYQuerenQuanCell") as? RYQuerenQuanCell
            cell?.selectionStyle = .none
            cell!.currentVC = self
            return cell!
        } else if indexPath.row == 2 {
            let cell: RYQuerenPeisongCell? = tableView.dequeueReusableCell(withIdentifier: "RYQuerenPeisongCell") as? RYQuerenPeisongCell
            cell?.selectionStyle = .none
            cell!.currentVC = self
            return cell!
        }  else if indexPath.row == 3 {
            let cell: RYQuerenDizhiCell? = tableView.dequeueReusableCell(withIdentifier: "RYQuerenDizhiCell") as? RYQuerenDizhiCell
            cell?.selectionStyle = .none
            if let m = addressModel {
                cell?.configure(m)
                self.params["shippingAddressId"] = m.id
            }
            cell!.currentVC = self
            return cell!
        } else if indexPath.row == 4{
            let cell: RYQuerenRenCell? = tableView.dequeueReusableCell(withIdentifier: "RYQuerenRenCell") as? RYQuerenRenCell
            cell?.selectionStyle = .none
            cell!.currentVC = self
            return cell!
        } else {
            let cell: RYQuerenPayCell? = tableView.dequeueReusableCell(withIdentifier: "RYQuerenPayCell") as? RYQuerenPayCell
            cell?.selectionStyle = .none
            cell!.currentVC = self
            return cell!
            
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 1 {
            
            let vc = RYQuanViewController()
            self.navigationController?.pushViewController(vc, animated: true)
        } else if indexPath.row == 2 {
            
        } else if indexPath.row == 3 {
            
            let vc = RYDizhiViewController()
            vc.passParamsClosure = {[weak self] param in
                if let `self` = self {
                    self.addressModel = (param as! RYAddressListModel)
                    self.tableView.reloadData()
                }
                
            }
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let v = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 0.01.autoWidth()))
        v.backgroundColor = Constant.bgViewColor
        return v
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let v = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 10.autoWidth()))
        v.backgroundColor = Constant.bgViewColor
        return v
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10.autoWidth()
    }
    
}
